var express = require('express'),
  http = require("http"),
  https = require("https"),
  fs = require('fs'),
  url = require("url"),
  path = require("path"),
  hjs = require('hjs'),
  api = require("./interface").api,
  s_config = require("./user/server-config.js").config,
  routes = require('./routes'),
  os = require('os'),
  numCPUs = os.cpus().length,
  cluster = require('cluster'),
  domainA = require('domain'),
  cors = require('cors'),
  helmet = require('helmet');

var session = require('express-session');
var cookieParser = require('cookie-parser');

function errorHandler(err, req, res, next) {
  console.log("ERROR: ", err);
  res.status(404);
  res.render('404', {});
}

function start() {

  var app = express();

  app.set('env', 'development');
  app.set('view engine', 'hjs');
  app.use(express.compress({
    filter: function(req, res) {
      return /json|text|javascript|css|ttf|woff|eot|svg/.test(res.getHeader('Content-Type'));
    },
    level: 9
  }));
  app.use(express.favicon(__dirname + '/favicon.ico'));
  app.use(express.logger());
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(helmet());
  app.use(helmet.noCache())
  app.use(cors()); 

  if ('development' == app.get('env')) {
    app.set('hostname', s_config.ip);
    app.set('port', s_config.port);
    app.set('views', __dirname + "/views");
    app.use("/", express.static(path.join(__dirname, '/public')));
    app.use(errorHandler);
  }

  if ('production' == app.get('env')) {
    app.set('hostname', '127.0.0.1')
    app.set('port', 3000);
    app.set('views', __dirname + "/views");
    app.use("/", express.static(path.join(__dirname, '/public')));
  }

  app.use(cookieParser());
  app.use(session({
    secret: (Math.random(1000) + "").replace(/\./gim, ""),
    cookie: {
      maxAge: 60 * 1000 * 30
    } // 过期时间（毫秒）
  }));

  app.use(app.router);

  //var RateLimit = require('express-rate-limit');

  app.enable('trust proxy');

  /*var apiLimiter = new RateLimit({
    windowMs: 0.5 * 60 * 1000, // 15 minutes
    max: 1000,
    delayMs: 0 // disabled
  });
  app.use(apiLimiter);*/

  app.locals({
    title: 'yd',
    email: '18900360@qq.com',
    phone: '15801483876'
  });

  if (cluster.isMaster) {
    os.cpus().forEach(function() {
      cluster.schedulingPolicy = cluster.SCHED_NONE;
      var work_process = cluster.fork();
      work_process.on('message', function(msg) {
        //console.log('get message: ' + msg.cmd)
      });
    });

    cluster.on("death", function() {
      console.log('[master] ' + worker.pid + ' died. restart...');
      process.nextTick(function() {
        cluster.fork();
      });
    });

    cluster.on('fork', function(worker) {
      console.log('[master] ' + 'fork: worker' + worker.id);
    });

    cluster.on('online', function(worker) {
      console.log('[master] ' + 'online: worker' + worker.id);
    });

    cluster.on('listening', function(worker, address) {
      console.log('[master] ' + 'listening: worker' + worker.id + ',pid:' + worker.process.pid + ', Address:' + address.address + ":" + address.port);
    });

    cluster.on('disconnect', function(worker) {
      console.log('[master] ' + 'disconnect: worker' + worker.id);
    });

    cluster.on('exit', function(worker, code, signal) {
      console.log('[master] ' + 'exit worker' + worker.id + ' died');
    });
  } else if (cluster.isWorker) {
    console.log('[worker] ' + "start worker ..." + cluster.worker.id);
    process.on('message', function(msg) {
      console.log('[worker] ' + msg);
      process.send('[worker] worker' + cluster.worker.id + ' received!');
    });

    var domain = domainA.create();

    var connect = http.createServer(app).listen(app.get('port'), s_config.ip, function() {
      console.log('server start.')
      console.log('port: ' + app.get('port'))
        /*process.send({
          cmd: 'send message!'
        });*/
    });
    connect.domain = domain;
    domain.on('error', function(err) {
      console.log('domain error: ' + err)
    });

    /*var domainB = domainA.create();

    var connect = https.createServer({
      key: fs.readFileSync(path.join(__dirname, '/__sys/server.key')),
      cert: fs.readFileSync(path.join(__dirname, '/__sys/server.crt'))
    }, app).listen(443, s_config.ip, function() {
      console.log('server start.')
      console.log('port: ' + 443)
        process.send({
          cmd: 'send message!'
        });
    });
    connect.domain = domainB;
    domainB.on('error', function(err) {
      console.log('domain error: ' + err)
    });*/


    api({
      app: app,
      routes: routes,
      s_config: s_config,
      cluster: cluster,
      url: url,
      //RateLimit: RateLimit,
      wss: null
    });

  }
}

exports.start = start;